﻿using Sustainalytics.BusinessResearchProductStates.Entities.ResearchState;
using Sustainalytics.ClientDW.Entities;
using Sustainalytics.DataLayer.Shared;
using Sustainalytics.Entities;
using Sustainalytics.FileManager;
using Sustainalytics.Synchronization.Interface;
using Sustainalytics.Utils;
using System;
using System.Linq;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using Xunit;


namespace Sustainalytics.GCCS.CompanyReportSyncStep
{
    public class GenerateGccsPdfReportsTests
    {
        [Fact]
        public void GeneratePdfReportTest()
        {
            var clientDwConnectionString = "mongodb://sustadmin:G4nd4lf2014@54.171.12.91/ClientDW_B";
            var path = @"E:\Reports\";

            var bulkSize = 500;
            var maxDegreeOfParallelism = ParallelHelper.GetMaxDegreeOfParallelism();


            var syncContext = new SyncContext
            {
                LastSyncTime = null,
                GAConnectionStrings = new Dictionary<string, string>
                {
                    {"ClientDW", clientDwConnectionString}
                },
                PreviousChanges = new List<ChangedElement>(),
                Report = new ConcurrentBag<string>()
            };

            var bulkDataReader = new GCCSReportBulkDataReader(bulkSize, clientDwConnectionString, syncContext.Token, maxDegreeOfParallelism);


            var currentQuarterRepo = new RepositoryCollection<GCCurrentQuarter>(clientDwConnectionString);
            
            var imageFileManager = new DiskFileManager(@"Images\GcPdfExport");


            var gcExportManager = new GCExportManager(currentQuarterRepo, imageFileManager, null, null, null, null);


            var companyProfileResearchStateCollection = new RepositoryCollection<GCOverallCompanySummary>(clientDwConnectionString);
            var companyProfiles = companyProfileResearchStateCollection.ReadWhere(x => x.OverallCompanyAssessment > 0);
            
            var companyIds = companyProfiles.Select(x => x.Id).ToList();


            //var companyIds = new List<Guid>
            //{
            //    new Guid("6c6845ff-4d9e-4f4d-b920-962af834ef0a")
            //};

            var batch = bulkDataReader.NextBulk(companyIds);

            foreach (var reportData in batch)
            {
                try
                {


                    if (reportData.OverallCompanySummary == null)
                    {
                        syncContext.Log(string.Format("Company profile with Id {0} has OverallCompanySummary == null", reportData.CompanyId));
                        return;
                    }

                    if (reportData.Principles.Count <= 0) continue;

                    var sw = Stopwatch.StartNew();

                    var gccsPdfReportContent = gcExportManager.GeneratePdfReport(reportData.CurrentQuarter,
                        reportData.Assessment, false,
                        reportData.OverallCompanySummary, reportData.Principles, reportData.PrincipleEventIndicators,
                        reportData.Sources);

                    var renderResult = new GccsReport
                    {
                        Id = Guid.NewGuid(),
                        CompanyId = reportData.CompanyId,
                        Assessment = reportData.Assessment,
                        FileContent = gccsPdfReportContent,
                        MimeType = "application/pdf"
                    };

                    var companyName = reportData.OverallCompanySummary.CompanyProfile.Name;
                    var dateTime = reportData.CurrentQuarter.Date;
                    renderResult.FileName = reportData.Assessment.GetFullReportName(companyName, dateTime);

                    File.WriteAllBytes(path +
                                       string.Format("{0}_{1}{2}",
                                           renderResult.Assessment == GCAssessment.NonCompliant ? "NC" : "WL",
                                           renderResult.FileName, ".pdf"),
                        renderResult.FileContent);

                    sw.Stop();

                    syncContext.Log(
                        string.Format(
                            "{0} has report generated succesfully for assesment: {1}. Company ID: {2}. Elapsed time:{3}",
                            reportData.OverallCompanySummary.CompanyProfile.Name, reportData.Assessment,
                            reportData.CompanyId, sw.Elapsed));
                }
                catch (Exception ex)
                {

                }
            }

        }
    }
}
